<template>
  <div>
    <el-row :gutter="10">
      <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"
        ><div class="grid-content bg-purple">
          <el-button type="success" round @click="enter">进入聊天</el-button>
        </div></el-col
      >
      <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"
        ><div class="grid-content bg-purple-light">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="textarea"
          >
          </el-input>
          <el-button type="primary" @click="send">立即发送</el-button>
        </div></el-col
      >
      <el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"
        ><div class="grid-content bg-purple" id="left" v-text="leftName"></div
      ></el-col>
      <el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"
        ><div
          class="grid-content bg-purple-light"
          id="right"
          v-text="rightName"
        ></div
      ></el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存数据
    return {
      textarea: "",
      leftName: "我来了",
      rightName: "我又走了",
      webSocket: "",
    };
  },
  //计算属性
  computed: {},
  //监控data中数据变化
  watch: {},
  //方法
  methods: {
    init() {
      // alert("123");
      if (window.WebSocket) {
        this.webSocket = new WebSocket("ws://localhost:53134/ws");
      } else {
        alert("抱歉，您的浏览器不支持WebSocket协议!");
      }
      //   //连通之后的回调事件
      //   this.webSocket.onopen = function () {
      //     console.log("已经连通了websocket");
      //     //                setMessageInnerHTML("已经连通了websocket");
      //   };
      //连接发生错误的回调方法
      this.webSocket.onerror = function (event) {
        console.log("出错了");
        //              setMessageInnerHTML("连接失败");
      };

      //连接关闭的回调方法
      this.webSocket.onclose = function () {
        console.log("连接已关闭...");
      };

      //接收到消息的回调方法
      this.webSocket.onmessage = (event) => {
        console.log("bbdds");
        var data = JSON.parse(event.data);
        var msg = data.msg;
        var nick = data.sendUser;
        switch (data.type) {
          case "init":
            console.log("mmll");
            break;
          case "msg":
            console.log("bblld", msg, nick);
            // this.setMessageInnerHTML(nick + ":  " + msg);
            // this.leftName=nick + ":  " + msg;
            console.log(this, "------------------");
            this.leftName = nick + ":  " + msg;
            break;
          default:
            break;
        }
      };
    },

    enter() {
      // alert("456");
      // var map = new Map();
      // var nick = "lemon";
      // var room = "906";
      // map.set("type", "init");
      // map.set("nick", nick);
      // console.log(room);
      // map.set("room", room);
      // var message = this.Map2Json(map);
      // this.webSocket.send(message);

      var userId;
      var userName;
      this.$http({
        url: this.$http.adornUrl("/sys/user/info"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          alert(data.data.userId);
          userId = data.data.userId;
          userName = data.data.username;

          var map = new Map();
          map.set("type", "init");
          map.set("userId", 15);
          alert(userId);
          alert(userName);
          map.set("fromUserId", userId);
          map.set("userName", userName);
          var message = this.Map2Json(map);
          this.webSocket.send(message);
        }
      });
    },

    send() {
      var userId;
      this.$http({
        url: this.$http.adornUrl("/sys/user/info"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          userId = data.data.userId;
        }
      });

      // alert("789");
      var msg = this.textarea;
      // var nick = "lemon";
      console.log("1:" + msg);
      if (msg != null && msg != "") {
        var map = new Map();
        map.set("type", "msg");
        map.set("msg", msg);
        map.set("userId", userId);
        var map2json = this.Map2Json(map);
        if (map2json.length < 8000) {
          console.log("4:" + map2json);
          this.webSocket.send(map2json);
        } else {
          console.log("文本太长了，少写一点吧😭");
        }
      }
    },

    //将消息显示在网页上
    setMessageInnerHTML(innerHTML) {
      //   document.getElementById("message").innerHTML += innerHTML + "<br/>";
      this.leftName = innerHTML;
    },

    Map2Json(map) {
      var str = "{";
      map.forEach(function (value, key) {
        str += '"' + key + '"' + ":" + '"' + value + '",';
      });
      str = str.substring(0, str.length - 1);
      str += "}";
      return str;
    },

    // send() {},
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {
    // this.init();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //声明周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁之后
  activated() {
    // this.init();
  }, //缓存keep-alive
};
</script>

<style scoped>
</style>